import React, { Fragment, useState } from 'react'
import { connect } from 'react-redux'
import { Redirect, withRouter } from 'react-router-dom'
import { Input, Button, message } from 'antd'
import Cookies from 'js-cookie'
import { userLogin } from '../../request/user'
import { actionCreators } from '../../store'
import { TOKEN_KEY } from '../../constants'
import './style.scss'

function Login(props) {
  const { isLogin, setLoginStatus } = props
  const [account, setAccount] = useState('')
  const [password, setPassword] = useState('')

  const onAccountChange = e => {
    setAccount(e.target.value)
  }

  const onPasswordChange = e => {
    setPassword(e.target.value)
  }

  const loginBtnClick = async() => {
    if (!account.trim()) {
      message.warn('账户不能为空')
      return false
    }
    if (!password.trim()) {
      message.warn('密码不能为空')
      return false
    }
    const { code, message: errMsg, data } = await userLogin({ name: account.trim(), password: password.trim() })
    if (code) {
      message.error(errMsg)
      return false
    }
    const cookiesOption = { expires: 1 }
    Cookies.set(TOKEN_KEY, data.token, cookiesOption)
    setLoginStatus(true)
  }
  return (
    <div className="login">
      {isLogin
        ? (
          <Redirect to="/"/>
        ) : (
          <Fragment>
            <header>
              <div className="content">
                订单管理系统
              </div>
            </header>
            <div className="content">
              <div className="title">
                欢迎登录
              </div>
              <div className="form">
                <p>
                  <Input size="large" value={account} onChange={onAccountChange} placeholder="请输入账户"/>
                </p>
                <p>
                  <Input size="large" value={password} type="password" onChange={onPasswordChange} placeholder="请输入密码"/>
                </p>
                <p>
                  <Button size="large" className="login-btn" onClick={loginBtnClick} type="primary">立即登录</Button>
                </p>
              </div>
            </div>
          </Fragment>
        )}
    </div>
  )
}

export default connect(state => ({
  isLogin: state.getIn(['common', 'isLogin'])
}), dispatch => ({
  setLoginStatus(value) {
    dispatch(actionCreators.setLoginStatus(value))
  }
}))(withRouter(Login))
